//
//  YYECourseSearchViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2017/12/29.
//  Copyright © 2017年 胡波. All rights reserved.
//

#import "YYECourseSearchViewController.h"
#import "YYEHotCourseCollectionViewCell.h"
#import "YSLCustomButton.h"
#import "YYECourseModel.h"
#import "YYECoursePlayViewController.h"
#import "YYECourseNoBuyViewController.h"
#import "YYECourseLeftModel.h"

@interface YYECourseSearchViewController () <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic,strong) UIView *contentView;
@property (nonatomic,strong) YSLCustomButton *semesterBtn;
@property (nonatomic,strong) YSLCustomButton *priceBtn;
@property (nonatomic,strong) UIView *backView;
@property (nonatomic,strong) YYEBaseTableView *tableView;
@property (nonatomic,strong) UITapGestureRecognizer *tap;
@property (nonatomic,strong) UIButton *selectBtn;
@property (nonatomic,assign) NSInteger selectdIndex;
@property (nonatomic,strong) NSMutableArray *datas;
@property (nonatomic,strong) UITextField *contentTF;
@property (nonatomic,copy)   NSString *termID;
@property (nonatomic,copy)   NSString *priceID;
@property (nonatomic,strong) NSMutableArray *termsArr;
@property (nonatomic,strong) NSMutableArray *priceArr;
@property (nonatomic,assign) NSInteger page;


@end

@implementation YYECourseSearchViewController

static NSString *courseCell = @"courseCell";
static NSString *chooseCell = @"chooseCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
    
    self.priceID = @"";
    self.termID = @"";
    
    [self configUI];
    
    [self configNavi];
    
    [self loadData];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //    [header beginRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    self.collectionView.mj_header = header;
    
    
    // 上拉刷新
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self loadMoreData];
    }];
    
    [self loadNewData];
    
}

- (void)loadNewData {
    
    self.page = 1;
    [self loadDataWithPage:self.page];
    
}

- (void)loadMoreData {
    
    self.page ++ ;
    [self loadDataWithPage:self.page];
    
}

- (void)loadDataWithPage:(NSInteger)page {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token,
                          @"p":@(self.page),
                          @"size":@"10",
                          @"key":self.contentTF.text,
                          @"priceId":self.priceID,
                          @"termId":self.termID,
                          @"courseId":self.cid?self.cid:@""
                          };
    NSLog(@"参数是%@",dic);
    [SVProgressHUD show];
    [AFNHelper post:LessonSearch parameters:dic success:^(id responseObject) {
        
        NSLog(@"  %@ ",responseObject);
        if (self.page == 1) {
            [self.datas removeAllObjects];
        }
        if ([responseObject[@"status"] isEqual:@1]) {
            
            NSArray *courseArr = [YYECourseModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.datas addObjectsFromArray:courseArr];
//            self.datas = [YYECourseModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.collectionView reloadData];
            
        }
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        
        NSInteger totalPage = [responseObject[@"total_page"] integerValue];
        if (self.page == totalPage) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        [SVProgressHUD showWithStatus:ShowError];
        [SVProgressHUD dismiss];
        
    }];
    
}

- (void)configNavi {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(15, 6, SCREEN_WIDTH - 23, 32)];
    
    UIView *leftCV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 33, 30)];
    
    UIImageView *searchIV = [[UIImageView alloc]initWithFrame:CGRectMake(10, 6, 18, 18)];
    searchIV.image = [UIImage imageNamed:@"search"];
    [leftCV addSubview:searchIV];
    
    self.contentTF = [[UITextField alloc]initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH - 65, 30)];
    self.contentTF.placeholder = @"请输入搜索关键词";
    self.contentTF.backgroundColor = [UIColor whiteColor];
    [self.contentTF setValue:[UIFont systemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
    self.contentTF.text = self.searchText;
    self.contentTF.layer.cornerRadius = 15;
    self.contentTF.leftView = leftCV;
    self.contentTF.delegate = self;
    self.contentTF.leftViewMode = UITextFieldViewModeAlways;
    self.contentTF.returnKeyType = UIReturnKeySearch;
    [contentView addSubview:self.contentTF];
    
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(contentView.bounds.size.width - 38, 1, 35, 30)];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [cancelBtn addTarget:self action:@selector(cacenClicked) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:cancelBtn];
    
    self.navigationItem.titleView = contentView;
    
}

- (void)cacenClicked {
    
    [self.view endEditing:YES];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)loadData {
    
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.tableView.hidden = YES;
    self.backView.hidden = YES;
    
}

- (void)configUI {
    
    self.contentView = [[UIView alloc]init];
    self.contentView.backgroundColor = GeneralBackColor;
    [self.view addSubview:self.contentView];
    
    self.semesterBtn = [[YSLCustomButton alloc]init];
    [self.semesterBtn setTitle:@"学期排序" forState:UIControlStateNormal];
    [self.semesterBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.semesterBtn setTitleColor:GeneralBlueColor forState:UIControlStateSelected];
    self.semesterBtn.ysl_buttonType = YSLCustomButtonImageRight;
    self.semesterBtn.ysl_spacing = 5;
    self.semesterBtn.tag = 100;
    [self.semesterBtn setImage:[UIImage imageNamed:@"noselected"] forState:UIControlStateNormal];
    [self.semesterBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected];
//    self.semesterBtn.imageEdgeInsets = UIEdgeInsetsMake(0, self.semesterBtn.titleLabel.frame.size.width + 5, 0, 0);
    self.semesterBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.semesterBtn layoutIfNeeded];
    [self.semesterBtn addTarget:self action:@selector(semesterClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.semesterBtn];
    
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = LightLineColor;
    [self.contentView addSubview:lineView];
    
    self.priceBtn = [[YSLCustomButton alloc]init];
    [self.priceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.priceBtn setTitleColor:GeneralBlueColor forState:UIControlStateSelected];
    [self.priceBtn setTitle:@"价格排序" forState:UIControlStateNormal];
    self.priceBtn.ysl_buttonType = YSLCustomButtonImageRight;
    self.priceBtn.ysl_spacing = 5;
    self.priceBtn.tag = 101;
    [self.priceBtn setImage:[UIImage imageNamed:@"noselected"] forState:UIControlStateNormal];
    [self.priceBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected];
    [self.priceBtn addTarget:self action:@selector(semesterClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.priceBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    self.priceBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.priceBtn layoutIfNeeded];
    [self.contentView addSubview:self.priceBtn];
    
    self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[YYEHotCourseCollectionViewCell class] forCellWithReuseIdentifier:courseCell];
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight + 40, SCREEN_WIDTH, SCREEN_HEIGHT - SafeAreaTopHeight - 40)];
    self.backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.backView.hidden = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:self.backView];
    
    [self.backView addSubview:self.tableView];
    self.tableView.bounces = NO;
    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.tableView.tableFooterView = [self footerView];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:chooseCell];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    
    [self.contentView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.equalTo(40);
    }];
    
    [self.semesterBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self.contentView);
//        make.width.equalTo(SCREEN_WIDTH / 2);
        make.width.equalTo(SCREEN_WIDTH);
    }];
    
//    [lineView makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.contentView.top).offset(5);
//        make.left.equalTo(self.semesterBtn.right);
//        make.bottom.equalTo(self.contentView.bottom).offset(-5);
//        make.width.equalTo(0.5);
//    }];
//
//    [self.priceBtn makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.contentView.top);
//        make.right.equalTo(self.contentView.right);
//        make.bottom.equalTo(self.contentView.bottom);
//        make.left.equalTo(lineView.right);
//    }];
    
    [self.collectionView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(3);
        make.right.equalTo(self.view.right).offset(-3);
        make.top.equalTo(self.view.top).offset(40);
        make.bottom.equalTo(self.view.bottom);
    }];
    
}

- (YYEBaseTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableView;
    
}

- (NSMutableArray *)datas {
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
    
}

- (NSMutableArray *)termsArr {
    
    if (!_termsArr) {
        _termsArr = [NSMutableArray array];
    }
    return _termsArr;
    
}

- (NSMutableArray *)priceArr {
    
    if (!_priceArr) {
        _priceArr = [NSMutableArray array];
    }
    return _priceArr;
    
}

// 学期
- (void)semesterClicked:(YSLCustomButton *)button {
    
    self.selectdIndex = button.tag;
    if (button.tag == 100 && self.termsArr.count < 1) { // 学期
        
        [SVProgressHUD show];
        [AFNHelper post:TermList parameters:nil success:^(id responseObject) {
            
            NSLog(@"%@",responseObject);
            if ([responseObject[@"status"] isEqual:@1]) {
                self.termsArr = [YYECourseLeftModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
                [self.tableView reloadData];
            }
            [SVProgressHUD showWithStatus:responseObject[@"message"]];
            [SVProgressHUD dismiss];
            
        } faliure:^(id error) {
            
            NSLog(@"请求失败");
            [SVProgressHUD showWithStatus:ShowError];
            [SVProgressHUD dismissWithDelay:0.5];
            
        }];
        
    }else if (button.tag == 101 && self.priceArr.count < 1) {
        
        [SVProgressHUD show];
        [AFNHelper post:PriceList parameters:nil success:^(id responseObject) {
            
            NSLog(@"%@",responseObject);
            if ([responseObject[@"status"] isEqual:@1]) {
                self.priceArr = [YYECourseLeftModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
                [self.tableView reloadData];
            }
            [SVProgressHUD showWithStatus:responseObject[@"message"]];
            [SVProgressHUD dismiss];
            
        } faliure:^(id error) {
            
            NSLog(@"请求失败");
            [SVProgressHUD showWithStatus:ShowError];
            [SVProgressHUD dismissWithDelay:0.5];
            
        }];
        
    }
    
    button.selected = YES;
    if (self.selectBtn == button) {
        button.selected = YES;
    }else {
        button.selected = YES;
        self.selectBtn.selected = NO;
    }
    
    self.selectBtn = button;
    [self.tableView reloadData];
    self.tableView.hidden = NO;
    self.backView.hidden = NO;
    
}

#pragma mark -- UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.datas.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    YYEHotCourseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:courseCell forIndexPath:indexPath];
    
    cell.courseModel = self.datas[indexPath.row];
    
    return cell;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(SCREEN_WIDTH / 2 - 3, 71 + (SCREEN_WIDTH / 2 - 6) * 0.55);
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    YYECourseModel *model = self.datas[indexPath.row];
    YYECoursePlayViewController *playVC = [[YYECoursePlayViewController alloc]init];
    playVC.cid = model.id;
    [self.navigationController pushViewController:playVC animated:YES];
    
//    if ([LoginModel shareLogin].username.length > 0) {
//        
//
//        
//    }else {
//        
//        YYECourseNoBuyViewController *vc = [[YYECourseNoBuyViewController alloc]init];
//        vc.cid = model.id;
//        [self.navigationController pushViewController:vc animated:YES];
//        
//    }
    
}

#pragma mark -- UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.selectdIndex == 100) {
        return self.termsArr.count;
    }else if (self.selectdIndex == 101) {
        return self.priceArr.count;
    }
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:chooseCell];
    
    if (self.selectdIndex == 100) {
        cell.textLabel.text = [self.termsArr[indexPath.row] CateName];
    }else if (self.selectdIndex == 101) {
        cell.textLabel.text = [self.priceArr[indexPath.row] CateName];
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.selectdIndex == 100) {
        
        YYECourseLeftModel *model = self.termsArr[indexPath.row];
        self.termID = model.id;
        
        self.backView.hidden = YES;
        self.tableView.hidden = YES;
        
        [self loadNewData];
        
    }else if (self.selectdIndex == 101) {
        
        YYECourseLeftModel *model = self.priceArr[indexPath.row];
        self.priceID = model.id;
        
        self.backView.hidden = YES;
        self.tableView.hidden = YES;
        
        [self loadNewData];
        
    }
    
}

- (UIView *)footerView {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - SafeAreaTopHeight - 40)];
    self.tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClicked)];
    [contentView addGestureRecognizer:self.tap];
    
    return contentView;
    
}

- (void)tapClicked {
    
    [UIView animateWithDuration:0.5 animations:^{
        
//        self.tableView.center = CGPointMake(<#CGFloat x#>, <#CGFloat y#>)
        self.backView.hidden = YES;
    }];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    NSLog(@" %@ ",textField.text);
    [self loadNewData];
    
    return YES;
    
}

- (void)dealloc {
    
    [self.tableView removeFromSuperview];
    [self.backView removeFromSuperview];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
